package com.xiaoshangkou.hellopra.controller.frontdesk;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoshangkou.hellopra.bean.Result;
import com.xiaoshangkou.hellopra.bean.WangEditorResult;
import com.xiaoshangkou.hellopra.pojo.Member;
import com.xiaoshangkou.hellopra.pojo.Post;
import com.xiaoshangkou.hellopra.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/frontdesk")
public class FrontdeskMemberController {
    @Autowired
    private MemberService memberService;

    //注册
    @RequestMapping("/register")
    public ModelAndView register(Member member){

        ModelAndView modelAndView = new ModelAndView();
        //注册
        Result result=memberService.register(member);
        if (!result.isFlag()){//注册失败
            modelAndView.addObject("message",result.getMessage());
            modelAndView.setViewName("/frontdesk/register_fail");
        }else {//注册成功
            modelAndView.setViewName("/frontdesk/register_ok");
        }
        return modelAndView;
    }

    //登录
    @RequestMapping("/login")
    public ModelAndView login(String name,String password,HttpSession session){
        ModelAndView modelAndView = new ModelAndView();

        Result result=memberService.login(name,password);
        if (!result.isFlag()){//登录失败
            modelAndView.addObject("message",result.getMessage());
            modelAndView.setViewName("/frontdesk/log_fail");

        }else {//登录成功
            //将用户信息存入session
            session.setAttribute("member",result.getData());
            //重定向到生活趣事版块
            modelAndView.setViewName("redirect:/frontdesk/post/routeList?cid=18");

        }
        return modelAndView;
    }

    //个人主页
    @RequestMapping("/member/personalPage")
    public ModelAndView personalPage(Integer mid,@RequestParam(defaultValue = "1") int pagex,
                                     @RequestParam(defaultValue = "6") int size){
        Member member = memberService.findByMid(mid);
        List<Post> postByMid = memberService.findPostByMid(mid);
        // 分页代码片段
        // T表示对象实体 list是所要处理的列表数据
        Page<Post> page = new Page<>(pagex,size);
        page.setRecords(new ArrayList<>());
        page.setTotal(postByMid.size());
        // 当前页第一条数据在List中的位置
        int start = (int)((page.getCurrent() - 1) * page.getSize());
        // 当前页最后一条数据在List中的位置
        int end = (int)((start + page.getSize()) > postByMid.size() ? postByMid.size() : (page.getSize() * page.getCurrent()));

        if (page.getSize()*(page.getCurrent()-1) <= page.getTotal()) {
            // 分隔列表 当前页存在数据时 设置
            page.setRecords(postByMid.subList(start, end));
        }
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("postPage",page);
        modelAndView.setViewName("/frontdesk/personal_page");
        return modelAndView;
    }

    //修改信息
    //上传图片
    @RequestMapping("/member/upload")
    @ResponseBody//不会跳转页面,返回字符串（json数据）
    public WangEditorResult upload(HttpServletRequest request, MultipartFile file) throws IOException {

        //创建文件夹，存放上传文件
        //拿到上传文件名
        String filename = file.getOriginalFilename();
        filename= UUID.randomUUID()+filename;
        //1设置上传文件夹的真实路径
        //配置图片上传路径，注意此处的路径和MyMvcConfig.java中配置的路径保持一致
        File uploadPathFile = new File("src/main/resources/static/"+ "/upload/img/member/");


//        String realPath = ResourceUtils.getURL("classpath:").getPath() + "src/main/resources/static/upload";
        // 构建真实的文件路径
        File dir = new File(uploadPathFile.getAbsolutePath() + File.separator + filename);
        if (dir.exists()){
            dir.mkdirs();
        }

//        //创建空文件
//        File newFile = new File(dir, filename);
        //将上传的文件写到空文件夹中
        file.transferTo(dir);

        //构造返回结果
        WangEditorResult wangEditorResult = new WangEditorResult();
        wangEditorResult.setErrno(0);
        String[] data={"/upload/img/member/"+filename};
        wangEditorResult.setData(data);

        return  wangEditorResult;

    }
    //更新信息
    @RequestMapping("/member/update")
    public String update(Member member,HttpSession session){
        memberService.update(member,session);

        return "redirect:/frontdesk/member/personalPage";//重定向
    }

    //更新信息
    @RequestMapping("/member/stopCar")
    public String stopCar(HttpServletResponse response){
//        response.setHeader("X-Frame-Options", "SAMEORIGIN");// 解决IFrame拒绝的问题

        return "redirect:/frontdesk/map";//重定向
    }


    //登出
    @RequestMapping("/member/logout")
    public String logout(HttpSession session){
        session.removeAttribute("member");
        return "redirect:/frontdesk/post/routeList?cid=18";
    }



}
